package com.boss.oss.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

/**
 * OSS持久层
 * @author Hu_liantian
 * @date 2020/07/27
 */
@Repository
public class OssDao {

    @Autowired
    OSS ossClint;

    @Value("${bucket}")
    private String bucket;

    @Value("${fileUrl}")
    private String fileUrl;

    /**
     * 上传/修改文件
     * @author Hu_liantian
     * @date 2020/07/27
     */
    public void insertFile(File file) {
        try {
            ossClint.putObject(bucket,fileUrl+file.getName(),new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @author Hu_liantian
     * @date 2020/07/27
     */
    public void removeFile(String fileName) {
        ossClint.deleteObject(bucket,fileUrl+fileName);
    }

    /**
     * 查询文件
     * @author Hu_liantian
     * @date 2020/07/27
     */
    public List queryFile() {
        List<OSSObjectSummary> list = ossClint.listObjects(bucket).getObjectSummaries();
        return list;
    }

    /**
     * 下载文件
     * @author Hu_liantian
     * @date 2020/07/27
     */
    public void downloadFile(String fileName, File file) {
        ossClint.getObject(new GetObjectRequest(bucket, fileUrl+fileName), file);
    }

    /**
     * 关闭
     * @author Hu_liantian
     * @date 2020/07/27
     */
    public void shutdown(){
        ossClint.shutdown();
    }

}
